<?php
/**
 * Created by PhpStorm.
 * User: 勇林
 * Date: 2015/12/18
 * Time: 16:42
 */

namespace app\controllers;

use app\models\GkyQyh;
use app\models\GkyQyhUser;
use app\models\GkyUser;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use Yii;
use app\common\utils\QyWechat;

class QyhController extends Controller
{

    public function actionIndex($id){

        //获取当前企业号
        $weaccount = GkyQyh::findOne(['id'=>$id]);

        $options = array(
            'token'=>'gky',   //填写应用接口的Token
            'encodingaeskey'=>$weaccount->aeskey,//填写加密用的EncodingAESKey
            'appid'=>$weaccount->corpid,  //填写高级调用功能的appid
        );
        $weObj = new QyWechat($options);
        $weObj->valid(); //注意, 企业号与普通公众号不同，必须打开验证，不要注释掉
        $type = $weObj->getRev()->getRevType();
        switch($type) {
            case QyWechat::MSGTYPE_TEXT:
            $weObj->text("hello, I'm wechat")->reply();
            exit;
            break;
            case QyWechat::MSGTYPE_EVENT:
                break;
            case QyWechat::MSGTYPE_IMAGE:
                break;
            default:
                $weObj->text("help info")->reply();
        }
    }

    /**
     * 企业号授权获取用户信息
     */
    public function actionOauth(){

        $code = isset($_GET['code'])?$_GET['code']:'';
        $options = array(
            'token'=>'gky',   //填写应用接口的Token
            'encodingaeskey'=>'pRuLXJLJR2OGfFMhEDtzv7qXW9GMqX9YXdXoH5UocAx',//填写加密用的EncodingAESKey
            'appid'=>'wx91d6852b806f2ab7',  //填写高级调用功能的appid
            'appsecret'=>'5H7VBRGGmX0B7FTwoMtNn2Fr3iYrcOWNlKofpYyrAdPZh1v85r4nBe6Ro7PCrUhN', //填写高级调用功能的密钥
        );
        $weObj = new QyWechat($options); //创建实例对象
        $userid = $weObj->getUserId($code,1);
        $userInfo = $weObj->getUserInfo($userid['UserId']);
        $qyhUser = GkyQyhUser::find()->where(['userid'=>$userInfo['userid']])->one();
        //不存在当前成员
        if($qyhUser == null){
            $qyhUser = new GkyQyhUser();
        }
        $qyhUser->userid = $userInfo['userid'];
        $qyhUser->name = isset($userInfo['name']) ? $userInfo['name'] : "未设置";
        $qyhUser->position = isset($userInfo['position']) ? $userInfo['position'] : "未设置";
        $qyhUser->mobile = isset($userInfo['mobile']) ? $userInfo['mobile'] : '未设置';
        $qyhUser->gender = isset($userInfo['gender']) ? $userInfo['gender'] : '1';
        $qyhUser->weixinid = isset($userInfo['weixinid']) ? $userInfo['weixinid'] : '';
        $qyhUser->avatar = isset($userInfo['avatar']) ? $userInfo['avatar'] : '';
        $qyhUser->status = isset($userInfo['status']) ? $userInfo['status'] : '1';
        $qyhUser->save();

        $this->redirect('http://gky.fukangyun.com/GkyWechat/qymain.html?userInfo='.json_encode(ArrayHelper::toArray($qyhUser)));

    }

}